package per.hx.bs.web.sys.controller;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import per.hx.bs.base.BaseController;
import per.hx.bs.base.annotation.BsCLog;
import per.hx.bs.base.domain.Tree;
import per.hx.bs.base.domain.ReturnDTO;
import per.hx.bs.entity.sys.SysRoleDO;
import per.hx.bs.entity.sys.SysUserDO;
import per.hx.bs.util.PageUtils;
import per.hx.bs.util.PasswordUtils;
import per.hx.bs.util.Query;
import per.hx.bs.utils.FileUpload;
import per.hx.bs.vo.MultipartFileVo;
import per.hx.bs.vo.SysUserVo;

import per.hx.bs.web.sys.service.SysDictService;
import per.hx.bs.web.sys.service.SysRoleService;
import per.hx.bs.web.sys.service.SysUserService;

import java.util.List;
import java.util.Map;

/**
 * @author HuXing
 * @date 2018/3/23  13:30
 */
@Controller
@RequestMapping("/sys/user")
public class UserController extends BaseController {

    private final String prefix = "system/user/";

    private final
    SysUserService sysUserService;
    private final
    SysRoleService sysRoleService;
    private final
    SysDictService sysDictService;

    @Autowired
    public UserController(SysUserService sysUserService, SysRoleService sysRoleService, SysDictService sysDictService) {
        this.sysUserService = sysUserService;
        this.sysRoleService = sysRoleService;
        this.sysDictService = sysDictService;
    }


    @RequiresPermissions("sys:user:user")
    @GetMapping(value = {"/", ""})
    public String user() {
        return prefix + "user";
    }

    @GetMapping(value = "/list")
    @ResponseBody
    public PageUtils list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);
        List<SysUserDO> sysUserList = sysUserService.list(query);
        int total = sysUserService.count(query);
        return new PageUtils(sysUserList, total);
    }


    @BsCLog("添加用户页面")
    @RequiresPermissions("sys:user:add")
    @GetMapping(value = "/add")
    public String add(Model model) {
        List<SysRoleDO> roles = sysRoleService.list();
        model.addAttribute("roles", roles);
        return prefix + "add";
    }

    @BsCLog("编辑用户页面")
    @RequiresPermissions("sys:user:edit")
    @GetMapping(value = "/edit/{id}")
    public String edit(Model model, @PathVariable("id") Long id) {
        SysUserDO userDO = sysUserService.get(id);
        model.addAttribute("user", userDO);
        List<SysRoleDO> roles = sysRoleService.list(id);
        model.addAttribute("roles", roles);
        return prefix + "edit";
    }

    @BsCLog("添加用户")
    @RequiresPermissions("sys:user:add")
    @PostMapping("/save")
    @ResponseBody
    public ReturnDTO save(SysUserDO sysUserDO) {
        sysUserDO.setPassword(PasswordUtils.entryptPassword(sysUserDO.getPassword()));
        if (sysUserService.save(sysUserDO) > 0) {
            return ReturnDTO.ok();
        }
        return ReturnDTO.error();
    }

    @BsCLog("管理员更新用户")
    @RequiresPermissions("sys:user:edit")
    @PostMapping(value = "/update")
    @ResponseBody
    public ReturnDTO update(SysUserDO sysUserDO) {

        if (sysUserService.update(sysUserDO) > 0) {
            return ReturnDTO.ok();
        }
        return ReturnDTO.error();
    }

    @BsCLog("用户更新个人信息")
    @RequiresPermissions("sys:user:edit")
    @PostMapping(value = "/updatePersonal")
    @ResponseBody
    public ReturnDTO updatePersonal(SysUserDO sysUserDO) {
        if (sysUserService.updatePersonal(sysUserDO) > 0) {
            return ReturnDTO.ok();
        }
        return ReturnDTO.error();
    }

    @RequiresPermissions("sys:user:remove")
    @BsCLog("删除用户")
    @PostMapping(value = "/remove")
    @ResponseBody
    public ReturnDTO remove(Long id) {
        if (sysUserService.remove(id) > 0) {
            return ReturnDTO.ok();
        }
        return ReturnDTO.error();
    }

    @BsCLog("批量删除用户")
    @RequiresPermissions("sys:user:remove")
    @PostMapping(value = "/batchRemove")
    @ResponseBody
    public ReturnDTO batchRemove(@RequestParam("ids[]") Long[] userIds) {
        if (sysUserService.batchRemove(userIds) > 0) {
            return ReturnDTO.ok();
        }
        return ReturnDTO.error();
    }

    @BsCLog("检查用户是否存在")
    @PostMapping(value = "/exit")
    @ResponseBody
    public boolean exit(@RequestParam Map<String, Object> params) {
        // 存在，不通过，false
        return !sysUserService.exit(params);
    }

    @BsCLog("进入用户更改密码界面")
    @RequiresPermissions("sys:user:resetPwd")
    @GetMapping("/resetPwd/{id}")
    public String resetPwd(@PathVariable("id") Long userId, Model model) {
        SysUserDO sysUserDO = new SysUserDO();
        sysUserDO.setUserId(userId);
        model.addAttribute("user", sysUserDO);
        return prefix + "resetPwd";
    }

    @BsCLog("用户提交更改用户密码")
    @PostMapping(value = "/resetPwd")
    @ResponseBody
    public ReturnDTO resetPwd(SysUserVo sysUserVo) {
        try {
            sysUserVo.setSysUserDO(getUser());
            return sysUserService.resetPwd(sysUserVo);
        } catch (Exception e) {
            return ReturnDTO.error(1, e.getMessage());
        }
    }

    @BsCLog("admin提交更改用户密码")
    @RequiresPermissions("sys:user:resetPwd")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    public ReturnDTO adminResetPwd(SysUserVo sysUserVo) {
        try {
            sysUserService.adminResetPwd(sysUserVo);
            return ReturnDTO.ok();
        } catch (Exception e) {
            return ReturnDTO.error();
        }
    }

    @BsCLog("进入树形列表")
    @GetMapping("/treeView")
    public String treeView() {
        return prefix + "userTree";
    }

    @BsCLog("获取部门树形数据")
    @GetMapping(value = "/tree")
    @ResponseBody
    public Tree tree(@RequestParam Map<String, Object> map) {
        return JSON.parseObject(sysUserService.getTree(map), Tree.class);
    }

    @BsCLog("查看个人信息")
    @GetMapping(value = "/personal")
    public String personal(Model model) {
        model.addAttribute("user", getUser());
        model.addAttribute("hobbyList", sysDictService.getHobbyList(getUser()));
        model.addAttribute("sexList", sysDictService.getSexList());
        return prefix + "personal";
    }

    @PostMapping(value = "/uploadImg")
    @ResponseBody
    public ReturnDTO uploadImg(@RequestParam("avatarFile") MultipartFile file, String avatarData) {
        Map<String, Object> result;
        try {
            result = FileUpload.updatePersonalImg(new MultipartFileVo(getUserId(), avatarData, file), getUserId());
        } catch (Exception e) {
            return ReturnDTO.error("更新图像失败！");
        }
        if (result != null && result.size() > 0) {
            return ReturnDTO.ok(result);
        } else {
            return ReturnDTO.error("更新图像失败！");
        }
    }
}
